<!--  -->
<template>
  <div style="margin: 40px">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="用户名称：">
        <el-input v-model="formInline.uName" placeholder="审批人" />
      </el-form-item>
      <el-form-item label="所在省：">
        <el-select v-model="formInline.shengId" @change="shengChange(formInline.shengId)">
          <el-option label="请选择" :value="0" />
          <el-option v-for="(region,index) in regionShengList" :key="index" :label="region.name" :value="region.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="regionShiList.length>0" label="所在市：">
        <el-select v-model="formInline.shiId">
          <el-option label="请选择" :value="0" />
          <el-option v-for="(region,index) in regionShiList" :key="index" :label="region.name" :value="region.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserList">查询</el-button>
        <el-button type="primary" @click="addUser">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="userList" style="width: 100%">
      <el-table-column prop="id" label="编号" width="180" />
      <el-table-column prop="name" label="姓名" width="180" />
      <el-table-column prop="idNo" label="证件号" width="180" />
      <el-table-column prop="birthday" label="出生日期" width="180" />
      <el-table-column prop="shi.name" label="所在市" width="180" />
      <el-table-column prop="sheng.name" label="所在省" width="180" />
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <el-button type="success" icon="el-icon-edit" @click="editUser(scope.row)" />
          <el-button type="success" icon="el-icon-share" @click="showUser(scope.row)" />
          <el-button type="success" icon="el-icon-delete" @click="delUserById(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="opr" :visible.sync="dialogFormVisible">
      <el-form ref="userForm" :model="formUser" :disabled="opr==='显示'" :rules="rule">
        <el-form-item label="用户名称:" prop="name" :label-width="formLabelWidth">
          <el-input v-model="formUser.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="证件号码:" :label-width="formLabelWidth">
          <el-input v-model="formUser.idNo" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户生日:" :label-width="formLabelWidth">
          <el-date-picker
            v-model="formUser.birthday"
            clearable
            style="width: 100%"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="所在省:" :label-width="formLabelWidth">
          <el-select v-model="formUser.sheng.id" @change="shengChangeForm(formUser.sheng.id)">
            <el-option label="请选择" :value="0" />
            <el-option
              v-for="(region,index) in regionFromShengList"
              :key="index"
              :label="region.name"
              :value="region.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="regionFromShiList.length>0" label="所在市:" :label-width="formLabelWidth">
          <el-select v-model="formUser.cityId">
            <el-option label="请选择" :value="0" />
            <el-option
              v-for="(region,index) in regionFromShiList"
              :key="index"
              :label="region.name"
              :value="region.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户头像" :label-width="formLabelWidth">
          <el-input v-model="formUser.picture" style="display: none" class="id" />
          <single-upload v-model="formUser.picture" />
        </el-form-item>
      </el-form>
      <div v-if="opr!=='显示'" slot="footer" class="dialog-footer">
        <el-button @click="closeForm">取 消</el-button>
        <el-button type="primary" @click="confirmForm">确 定</el-button>
      </div>
      <div v-else slot="footer" class="dialog-footer">
        <el-button @click="closeForm">确 定</el-button>
      </div>
    </el-dialog>
    <div class="block" style="margin: 20px">
      <el-pagination
        :page-sizes="[2,3,5]"
        :page-size="formInline.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { delUser, getUserPage, saveUser, getInfoByName } from '@/api/csuser'
import { regionList } from '@/api/csregion'
import singleUpload from '@/components/upload/singleUpload.vue'

export default {
// import引入的组件需要注入到对象中才能使用
  components: {
    singleUpload
  },
  data() {
    // 这里存放数据
    var validateName = (rule, value, callback) => {
      console.log('name', value)
      getInfoByName(value).then(res => {
        console.log(res.data)
        if (this.formUser.id === 0 && res.data !== null) {
          callback(new Error('用户名已存在'))
        }
      })
    }
    return {
      formInline: {
        uName: '',
        shengId: 0,
        shiId: 0,
        pageIndex: 1,
        pageSize: 2
      },
      formUser: {
        id: 0,
        name: '',
        sheng: { id: 0, name: '' },
        shi: { id: 0, name: '' },
        idNo: '',
        birthday: '',
        cityId: 0,
        picture: ''
      },
      rule: {
        name: [{ required: true, message: '用户名不可为空', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }]
      },
      opr: '新增',
      regionShengList: [],
      regionFromShengList: [],
      regionShiList: [],
      regionFromShiList: [],
      regionLists: [],
      userList: [],
      total: 0,
      dialogFormVisible: false,
      formLabelWidth: '120px'
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getUserList()
    this.initRegion()
  },
  // 方法集合
  methods: {
    closeForm() {
      this.dialogFormVisible = false
      this.formUser = {
        id: 0,
        name: '',
        sheng: { id: 0, name: '' },
        shi: { id: 0, name: '' },
        idNo: '',
        birthday: '',
        cityId: 0,
        picture: ''
      }
    },
    confirmForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          console.log(this.formUser)
          saveUser(this.formUser).then(res => {
            this.dialogFormVisible = false
            this.getUserList()
            this.formUser = {
              id: 0,
              name: '',
              sheng: { id: 0, name: '' },
              shi: { id: 0, name: '' },
              idNo: '',
              birthday: '',
              cityId: 0,
              picture: ''
            }
            this.regionFromShengList = []
          })
        }
      })
    },
    addUser() {
      this.dialogFormVisible = true
      this.opr = '新增'
      this.formUser = {
        id: 0,
        name: '',
        sheng: { id: 0, name: '' },
        shi: { id: 0, name: '' },
        idNo: '',
        birthday: '',
        cityId: 0,
        picture: ''
      }
    },
    editUser(user) {
      this.opr = '修改'
      this.formUser = user
      this.dialogFormVisible = true
      console.log('省:', user.sheng.id)
      // eslint-disable-next-line no-array-constructor
      var array = new Array()
      this.regionLists.forEach((res) => {
        if (res.parentId === user.sheng.id) {
          array.push(res)
        }
      })
      this.regionFromShiList = array
    },
    showUser(user) {
      this.opr = '显示'
      this.formUser = user
      this.dialogFormVisible = true
      // eslint-disable-next-line no-array-constructor
      var array = new Array()
      this.regionLists.forEach((res) => {
        if (res.parentId === user.sheng.id) {
          array.push(res)
        }
      })
      this.regionFromShiList = array
      console.log('省', user.sheng.id)
    },
    getUserList() {
      getUserPage(this.formInline).then(res => {
        console.log(res.data)
        this.userList = res.data.records
        this.total = res.data.total
        console.log(this.total)
      })
    },
    delUserById(user) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(user.id).then(res => {
          this.getUserList()
        })
      })
    },
    initRegion() {
      regionList().then(res => {
        if (res.code === 200) {
          this.regionLists = res.data
          this.regionFromShengList = []
          this.regionShengList = []
          this.regionLists.forEach(region => {
            if (region.parentId === 0) {
              this.regionShengList.push(region)
              this.regionFromShengList.push(region)
            }
          })
        }
      })
    },
    shengChange(id) {
      this.formInline.shiId = 0
      this.regionShiList = []
      this.regionLists.forEach(region => {
        if (region.parentId === id && id !== 0) {
          this.regionShiList.push(region)
        }
      })
    },
    shengChangeForm(id) {
      console.log(id)
      this.formUser.cityId = 0
      this.regionFromShiList = []
      this.regionLists.forEach(region => {
        if (region.parentId === id && id !== 0) {
          this.regionFromShiList.push(region)
        }
      })
    },
    handleSizeChange(val) {
      this.formInline.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.formInline.pageIndex = val
      this.getUserList()
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>

</style>
